package com.zjzywl.smoke.controller;

/*
 * 巡更控制类
 */
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.zjzywl.smoke.entity.PatrolPeople;
import com.zjzywl.smoke.entity.PatrolPoints;
import com.zjzywl.smoke.util.WebResult;

@RestController
@RequestMapping(value = "/patrol")
public class PatrolPointsController extends BaseController {

    // 保存，修改巡更点信息
    @PostMapping(value = "/points/{orgId}")
    public WebResult save(HttpServletRequest request, @RequestBody PatrolPoints pp,
            @PathVariable("orgId") Integer orgId) {
        try {
            ResponseEntity<PatrolPoints> newpp = appConfig.restTemplate()
                    .postForEntity(appConfig.getGetDataIp() + "/patrol/points/" + orgId, pp, PatrolPoints.class);
            return WebResult.OK(newpp);
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }
    }

    // 删除巡更点信息
    @DeleteMapping("/points/{id}")
    public WebResult delete(@PathVariable("id") Integer id) {
        try {
            appConfig.restTemplate().delete(appConfig.getGetDataIp() + "/patrol/points/" + id);
            return WebResult.OK("巡更点删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL("巡更点删除失败");
        }
    }

    // 查询巡更点位
    @GetMapping("/points")
    public WebResult inquiry(HttpServletRequest request) {
        try {
            String userId = this.getUserId();
            ResponseEntity<Object> newpp = appConfig.restTemplate().getForEntity(
                    appConfig.getGetDataIp() + "/patrol/points/" + userId + "?" + request.getQueryString(),
                    Object.class);
            return WebResult.OK(newpp);
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL("巡更点查询失败");
        }
    }

    // 保存，修改巡更人员信息
    @PostMapping(value = "/patrolPeople/{orgId}")
    public WebResult savePatrolPeople(@RequestBody PatrolPeople pp, @PathVariable("orgId") Integer orgId) {
        try {
            ResponseEntity<PatrolPeople> newpp = appConfig.restTemplate()
                    .postForEntity(appConfig.getGetDataIp() + "/patrol/patrolPeople/" + orgId, pp, PatrolPeople.class);
            return WebResult.OK(newpp);
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL("巡更点添加失败");
        }
    }

    // 保存巡更人员头像
    @PostMapping(value = "/poplePhoto")
    public WebResult savePatrolPeople(HttpServletRequest request, MultipartFile multipartFile) {

        try {
            String tempFilePath = request.getSession().getServletContext().getRealPath("/")
                    + multipartFile.getOriginalFilename();
            File tempFile = new File(tempFilePath);
            HttpEntity<MultiValueMap<String, Object>> files = savePhoto(tempFile, multipartFile, tempFilePath);
            ResponseEntity<String> responseEntity = appConfig.restTemplate().postForEntity(
                    appConfig.getGetDataIp() + "/patrol/poplePhoto?id=" + request.getParameter("id"), files,
                    String.class);
            tempFile.delete();
            return WebResult.OK("图片上传成功");
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL("图片上传失败");
        }
    }

    // 删除巡更人员信息
    @DeleteMapping("/patrolPeople/{id}")
    public WebResult deletePatrolPeople(@PathVariable("id") Integer id) {
        try {
            appConfig.restTemplate().delete(appConfig.getGetDataIp() + "/patrol/patrolPeople/" + id);
            return WebResult.OK("巡更点删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL("巡更点删除失败");
        }
    }

    // 查询巡更人员位
    @GetMapping("/patrolPeople")
    public WebResult inquiryPatrolPeople(HttpServletRequest request) {

        try {
            String userId = this.getUserId();
            ResponseEntity<Object> newpp = appConfig.restTemplate().getForEntity(
                    appConfig.getGetDataIp() + "/patrol/patrolPeople/" + userId + "?" + request.getQueryString(),
                    Object.class);
            return WebResult.OK(newpp);
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL("巡更点查询失败");
        }
    }

    // 查询单个巡更人员的头像
    @GetMapping("/getPeoplePhoto/{id}")
    public void getPatrolPeoplePhoto(@PathVariable("id") Integer id, HttpServletResponse response) throws Exception {
        PatrolPeople cp = appConfig.restTemplate()
                .getForObject(appConfig.getGetDataIp() + "/patrol/getPeoplePhoto/" + id, PatrolPeople.class);
        String pictureFile = cp.getPhoto();
        getphoto(pictureFile, response);
    }

    // 巡更点位模糊查询
    @GetMapping("/getPatrolPoints")
    public WebResult getPatrolPoints(@RequestParam("name") String name) throws Exception {
        try {
            String userId = this.getUserId();

            Object forObject = appConfig.restTemplate().getForObject(
                    appConfig.getGetDataIp() + "/patrol/getPatrolPoints?userId=" + userId + "&name=" + name,
                    Object.class);
            return WebResult.OK(forObject);

        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }

    }

    // 保存巡更点二维码
    @PostMapping(value = "/qRCode")
    public WebResult saveqRCode(HttpServletRequest request, PatrolPoints patrolPoints, MultipartFile multipartFile) {

        try {
            String tempFilePath = request.getSession().getServletContext().getRealPath("/")
                    + multipartFile.getOriginalFilename();
            File tempFile = new File(tempFilePath);
            HttpEntity<MultiValueMap<String, Object>> files = savePhoto(tempFile, multipartFile, tempFilePath);
            patrolPoints.setqRCode(tempFilePath);
            ResponseEntity<String> responseEntity = appConfig.restTemplate()
                    .postForEntity(appConfig.getGetDataIp() + "/patrol/qRCode", patrolPoints, String.class);

            return WebResult.OK("图片上传成功");
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }
    }

    // 查询单个巡更点二维码
    @GetMapping("/qRCode/{id}")
    public void getQRCode(@PathVariable("id") Integer id, HttpServletResponse response) throws Exception {
        PatrolPoints cp = appConfig.restTemplate().getForObject(appConfig.getGetDataIp() + "/patrol/qRCode/" + id,
                PatrolPoints.class);
        String pictureFile = cp.getqRCode();
        getphoto(pictureFile, response);
    }

    private HttpEntity<MultiValueMap<String, Object>> savePhoto(File tempFile, MultipartFile multipartFile,
            String tempFilePath) throws IllegalStateException, IOException {
        HttpHeaders headers = new HttpHeaders();

        multipartFile.transferTo(tempFile);

        FileSystemResource fileSystemResource = new FileSystemResource(tempFilePath);
        MediaType type = MediaType.parseMediaType("multipart/form-data");
        headers.setContentType(type);
        String cd = "filename=\"" + multipartFile.getOriginalFilename() + "\"";
        headers.add("Content-Disposition", cd);
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
        form.add("file", fileSystemResource);

        HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);
        return files;
    }

    private void getphoto(String pictureFile, HttpServletResponse response) throws Exception {

        response.setContentType("image/jpeg ");
        FileInputStream fis = new FileInputStream(pictureFile);
        OutputStream os = response.getOutputStream();
        try {
            int count = 0;
            byte[] buffer = new byte[1024 * 1024];

            while ((count = fis.read(buffer)) != -1) {
                os.write(buffer, 0, count);
            }

        } catch (Exception e) {
            System.out.println("获取图片出错" + e);
        } finally {
            if (os != null)
                os.close();
            if (fis != null)
                fis.close();
        }
    }

}
